﻿using System;
using System.Data;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using ERP.Page;
using ET;
using BLL;
using HTML;

namespace ERP.PageUC
{
    public partial class TransactionUC : UserControl
    {
        #region[Define]
        protected string StrAlert = string.Empty;
        private readonly Transaction_BLL clsTransaction = new Transaction_BLL();
        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetTransaction();
                BindDropDown();
            }
        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            OpenDialog("#giaodich");
            ClearTextBox();
            upNewUpdatePanel.Update();
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < ListViewAll.Items.Count; i++)
            {
                var chkHide = (CheckBox)ListViewAll.Items[i].FindControl("chkList");
                if (chkHide.Checked)
                {
                    try
                    {
                        var dataKey = ListViewAll.DataKeys[i];
                        if (dataKey != null) Transaction_BLL.Deletetb_Transaction(int.Parse(dataKey.Value.ToString()));
                    }
                    catch
                    {
                        ((Label)Page.Master.FindControl("lbThongBao")).Text = "Chứng từ này còn tồn tại !";
                        OpenDialog("#thongbao");
                        ((UpdatePanel)Page.Master.FindControl("updatePanelThongBao")).Update();
                    }
                }
            }
            GetTransaction();
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            if (txtSearch.Text == "")
            {
                StrAlert = Alert.AlertWarning("Vui lòng nhập vào từ khoá tìm kiếm !");
            }
            else
            {
                GetTransaction();
            }
        }
        protected void btnReload_Click(object sender, EventArgs e)
        {
            txtSearch.Text = string.Empty;
            GetTransaction();
        }
        public void GetTransaction()
        {
            DataTable dtTransaction = clsTransaction.BindGirdtb_Transaction(txtSearch.Text);
            if (dtTransaction != null)
            {
                ListViewAll.DataSource = dtTransaction;
                ListViewAll.DataBind();
                if (txtSearch.Text != "" && dtTransaction.Rows.Count > 0)
                {
                    StrAlert = Alert.AlertSucess(dtTransaction.Rows.Count.ToString());
                }
            }
            else
            {
                StrAlert = Alert.AlertError("Bảng này không tồn tại");
            }
        }
        private void BindDropDown()
        {
            var clsKhachHang = new Customer_BLL();
            var dtKhachHang = clsKhachHang.BindGirdtb_Customer(string.Empty);
            if (dtKhachHang != null && dtKhachHang.Rows.Count > 0)
            {
                drKhachHang.Items.Clear();
                drKhachHang.Items.Add(new ListItem("-Vui lòng chọn khách hàng-", "-1"));
                drKhachHang.DataSource = dtKhachHang;
                drKhachHang.DataValueField = "Customer_Id";
                drKhachHang.DataTextField = "Customer_Alias";
                drKhachHang.DataBind();
            }

            var clsMucDich = new Destination_BLL();
            var dtMucDich = clsMucDich.BindGirdtb_Destination(string.Empty);
            if (dtMucDich != null && dtMucDich.Rows.Count > 0)
            {
                drMucDich.Items.Clear();
                drMucDich.Items.Add(new ListItem("-Vui lòng chọn mục đích-", "-1"));
                drMucDich.DataSource = dtMucDich;
                drMucDich.DataValueField = "Destination_Id";
                drMucDich.DataTextField = "Destination_Name";
                drMucDich.DataBind();
            }

            var clsPhuongThuc = new Method_BLL();
            var dtPhuongThuc = clsPhuongThuc.BindGirdtb_Method(string.Empty);
            if (dtPhuongThuc != null && dtPhuongThuc.Rows.Count > 0)
            {
                drPhuongThuc.Items.Clear();
                drPhuongThuc.Items.Add(new ListItem("-Vui lòng chọn phương thức-", "-1"));
                drPhuongThuc.DataSource = dtPhuongThuc;
                drPhuongThuc.DataValueField = "Method_Id";
                drPhuongThuc.DataTextField = "Method_Name";
                drPhuongThuc.DataBind();
            }
        }
        protected void btnSavePopup_Click(object sender, EventArgs e)
        {
            if (lbID.Value == "")
            {
                InsertTransaction();
            }
            else
            {
                UpdateTransaction();
            }
        }

        protected void btnReloadPopup_Click(object sender, EventArgs e)
        {
            BindDropDown();
        }
        protected bool CheckInsert()
        {
            bool kiemtra = false;
            var clsTransaction = new Transaction_BLL();
            var dtTransaction = clsTransaction.BindGirdtb_Transaction(string.Empty);
            if (dtTransaction != null && dtTransaction.Rows.Count > 0)
            {
                foreach (DataRow dr in dtTransaction.Rows)
                {
                    if (txtMaGiaoDich.Text == dr["Transaction_No"].ToString())
                    {
                        kiemtra = true;
                        if (Page.Master != null)
                            ((Label)Page.Master.FindControl("lbThongBao")).Text = "Trùng số giao dịch !";
                        OpenDialog("#thongbao");
                        if (Page.Master != null) ((UpdatePanel)Page.Master.FindControl("updatePanelThongBao")).Update();
                    }
                }
            }
            return kiemtra;
        }
        protected void InsertTransaction()
        {
            try
            {
                if (!CheckInsert())
                {
                    var obj = new Transaction_ET
                    {
                        Transaction_No = txtMaGiaoDich.Text,
                        Customer_ID = int.Parse(drKhachHang.SelectedValue),
                        Transaction_Date = DateTime.Parse(txtThoiGian.Text),
                        Method_ID = int.Parse(drPhuongThuc.SelectedValue),
                        Destination_ID = int.Parse(drMucDich.SelectedValue),
                        Transaction_Content = txtNoiDung.Text,
                        Transaction_Result = txtKetQua.Text,
                        Transaction_Note = txtGhiChu.Text,
                        Transaction_Available = rdbSanPhamDangDung.Checked,
                        Transaction_NotAvailable = rdbChuaCoNhuCau.Checked,
                        Transaction_Contact_Again = rdbLienHeLaiSau.Checked,
                        Transaction_Schedule = rdbLichHenLamViec.Checked,
                        Transaction_Available_Content = rdbSanPhamDangDung.Checked == true ? txtSanPhamDangDung.Text : string.Empty,
                        Transaction_NotAvailable_Content = rdbChuaCoNhuCau.Checked == true ? txtChuaCoNhuCau.Text : string.Empty,
                        Transaction_Contact_Again_Content = rdbLienHeLaiSau.Checked == true ? txtLienHeLaiSau.Text : string.Empty,
                        Transaction_Schedule_ID = 0,
                        Transaction_Potential = rdbDoiTuongCoTiemNang.Checked,
                        Transaction_NotPotential = rdbKhongCoTiemNang.Checked,
                        Transaction_Unknown = rdbChuaXacDinh.Checked,
                        Transaction_Date_Add = DateTime.Now,
                        Transaction_Date_Modify = DateTime.Now
                    };
                    Transaction_BLL.Inserttb_Transaction(obj);
                    ClearTextBox();
                    GetTransaction();
                    if (Page.Master != null)
                        ((Label)Page.Master.FindControl("lbThongBao")).Text = "Thêm mới thành công !";
                }
            }
            catch (Exception ex)
            {
                if (Page.Master != null) ((Label)Page.Master.FindControl("lbThongBao")).Text = ex.ToString();
            }
            finally
            {
                txtMaGiaoDich.Enabled = true;
                OpenDialog("#thongbao");
                if (Page.Master != null) ((UpdatePanel)Page.Master.FindControl("updatePanelThongBao")).Update();
            }
        }
        protected void UpdateTransaction()
        {
            try
            {
                var obj = new Transaction_ET
                {
                    Transaction_ID = int.Parse(lbID.Value),
                    Transaction_No = txtMaGiaoDich.Text,
                    Customer_ID = int.Parse(drKhachHang.SelectedValue),
                    Transaction_Date = DateTime.Parse(txtThoiGian.Text),
                    Method_ID = int.Parse(drPhuongThuc.SelectedValue),
                    Destination_ID = int.Parse(drMucDich.SelectedValue),
                    Transaction_Content = txtNoiDung.Text,
                    Transaction_Result = txtKetQua.Text,
                    Transaction_Note = txtGhiChu.Text,
                    Transaction_Available = rdbSanPhamDangDung.Checked,
                    Transaction_NotAvailable = rdbChuaCoNhuCau.Checked,
                    Transaction_Contact_Again = rdbLienHeLaiSau.Checked,
                    Transaction_Schedule = rdbLichHenLamViec.Checked,
                    Transaction_Available_Content = rdbSanPhamDangDung.Checked == true ? txtSanPhamDangDung.Text : string.Empty,
                    Transaction_NotAvailable_Content = rdbChuaCoNhuCau.Checked == true ? txtChuaCoNhuCau.Text : string.Empty,
                    Transaction_Contact_Again_Content = rdbLienHeLaiSau.Checked == true ? txtLienHeLaiSau.Text : string.Empty,
                    Transaction_Schedule_ID = 0,
                    Transaction_Potential = rdbDoiTuongCoTiemNang.Checked,
                    Transaction_NotPotential = rdbKhongCoTiemNang.Checked,
                    Transaction_Unknown = rdbChuaXacDinh.Checked,
                    Transaction_Date_Add = DateTime.Now,
                    Transaction_Date_Modify = DateTime.Now
                };
                Transaction_BLL.Updatetb_Transaction(obj);
                GetTransaction();
                if (Page.Master != null)
                    ((Label)Page.Master.FindControl("lbThongBao")).Text = "Sữa thành công !";
            }
            catch (Exception ex)
            {
                if (Page.Master != null) ((Label)Page.Master.FindControl("lbThongBao")).Text = ex.ToString();
            }
            finally
            {
                txtMaGiaoDich.Enabled = false;
                OpenDialog("#thongbao");
                if (Page.Master != null) ((UpdatePanel)Page.Master.FindControl("updatePanelThongBao")).Update();
            }
        }

        #region[OpenDialog]
        private void OpenDialog(string dialogId)
        {
            var sb = new StringBuilder();
            sb.Append("$('" + dialogId + "').dialog('open');");
            ScriptManager.RegisterStartupScript(Page, Page.GetType(),
                "scriptKey", sb.ToString(), true);
        }
        #endregion
        #region[ClearTextbox]
        protected void ClearTextBox()
        {
            txtMaGiaoDich.Text = MaTuDong();
            txtTenKhachHang.Text = string.Empty;
            txtThoiGian.Text = DateTime.Now.ToString();
            txtDiaChi.Text = string.Empty;
            txtMaSoThue.Text = string.Empty;
            txtLienhe.Text = string.Empty;
            txtChucVu.Text = string.Empty;
            txtNoiDung.Text = string.Empty;
            txtKetQua.Text = string.Empty;
            txtGhiChu.Text = string.Empty;
            txtSanPhamDangDung.Text = string.Empty;
            txtChuaCoNhuCau.Text = string.Empty;
            txtLienHeLaiSau.Text = string.Empty;
            txtLichHenLamViec.Text = string.Empty;

            drKhachHang.SelectedIndex = 0;
            drMucDich.SelectedIndex = 0;
            drPhuongThuc.SelectedIndex = 0;

            rdbSanPhamDangDung.Checked = false;
            rdbChuaCoNhuCau.Checked = false;
            rdbLienHeLaiSau.Checked = false;
            rdbLichHenLamViec.Checked = false;
            rdbDoiTuongCoTiemNang.Checked = false;
            rdbChuaXacDinh.Checked = false;
            rdbKhongCoTiemNang.Checked = false;
        }
        #endregion
        void DetailCustomer()
        {
            if (drKhachHang.SelectedValue == "-1")
            {
                txtTenKhachHang.Text = string.Empty;
                txtDiaChi.Text = string.Empty;
                txtMaSoThue.Text = string.Empty;
                txtLienhe.Text = string.Empty;
                txtChucVu.Text = string.Empty;
            }
            else
            {
                var clsKhachHang = new Customer_BLL();
                var dtKhachHang = clsKhachHang.GetCustomerDetail(int.Parse(drKhachHang.SelectedValue));
                if (dtKhachHang != null)
                {
                    txtTenKhachHang.Text = dtKhachHang.Rows[0]["Customer_Name"].ToString();
                    txtDiaChi.Text = dtKhachHang.Rows[0]["Customer_Address"].ToString();
                    txtMaSoThue.Text = dtKhachHang.Rows[0]["Customer_Contract_Tax_Code"].ToString();
                    txtLienhe.Text = dtKhachHang.Rows[0]["Contact_Name"].ToString();
                    txtChucVu.Text = dtKhachHang.Rows[0]["Job_Name"].ToString();
                }
            }
        }
        protected void drKhachHang_SelectedIndexChanged(object sender, EventArgs e)
        {
            DetailCustomer();
        }
        #region[MaTangTuDong]
        protected string MaTuDong()
        {
            int i = 0;
            DataTable dt = Transaction_BLL.cls.BindGirdtb_Transaction(string.Empty);
            if (dt != null && dt.Rows.Count > 0)
            {
                int max = Convert.ToInt32(dt.Rows[0]["Transaction_ID"].ToString());
                for (i = 0; i < dt.Rows.Count; i++)
                {
                    if (int.Parse(dt.Rows[i]["Transaction_ID"].ToString()) > max)
                    {
                        max = Convert.ToInt32(dt.Rows[i]["Transaction_ID"].ToString());
                    }
                }
                i = max + 1;
            }
            else
            {
                i = 0;
            }
            return "GD." + DateTime.Now.ToString("MMdd") + "-000" + i;
        }
        #endregion

        protected void ListViewAll_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            if (e.CommandName == "_ViewDetail")
            {
                Label lbIDQuotesDetail = (Label)e.Item.FindControl("lbIDDetail");
                GetTransactionDetail(int.Parse(lbIDQuotesDetail.Text));
                OpenDialog("#giaodich");
                txtMaGiaoDich.Enabled = false;
                upNewUpdatePanel.Update();
            }
        }

        private void GetTransactionDetail(int id)
        {
            DataTable dtTransaction = clsTransaction.BindGirdtb_TransactionDetail(id);
            if (dtTransaction != null)
            {
                lbID.Value = dtTransaction.Rows[0]["Transaction_ID"].ToString();
                txtMaGiaoDich.Text = dtTransaction.Rows[0]["Transaction_No"].ToString();
                drKhachHang.SelectedValue = dtTransaction.Rows[0]["Customer_ID"].ToString();
                DetailCustomer();
                txtThoiGian.Text = dtTransaction.Rows[0]["Transaction_Date"].ToString();
                drMucDich.SelectedValue = dtTransaction.Rows[0]["Destination_ID"].ToString();
                drPhuongThuc.SelectedValue = dtTransaction.Rows[0]["Method_ID"].ToString();
                txtNoiDung.Text = dtTransaction.Rows[0]["Transaction_Content"].ToString();
                txtKetQua.Text = dtTransaction.Rows[0]["Transaction_Result"].ToString();
                txtGhiChu.Text = dtTransaction.Rows[0]["Transaction_Note"].ToString();
                rdbSanPhamDangDung.Checked = dtTransaction.Rows[0]["Transaction_Available"].ToString() == "True" ? true : false;
                txtSanPhamDangDung.Text = dtTransaction.Rows[0]["Transaction_Available_Content"].ToString();
                rdbChuaCoNhuCau.Checked = dtTransaction.Rows[0]["Transaction_NotAvailable"].ToString() == "True" ? true : false;
                txtChuaCoNhuCau.Text = dtTransaction.Rows[0]["Transaction_NotAvailable_Content"].ToString();
                rdbLienHeLaiSau.Checked = dtTransaction.Rows[0]["Transaction_Contact_Again"].ToString() == "True" ? true : false;
                txtLienHeLaiSau.Text = dtTransaction.Rows[0]["Transaction_Contact_Again_Content"].ToString();
                rdbLichHenLamViec.Checked = dtTransaction.Rows[0]["Transaction_Schedule"].ToString() == "True" ? true : false;
                //********
                rdbDoiTuongCoTiemNang.Checked = dtTransaction.Rows[0]["Transaction_Potential"].ToString() == "True" ? true : false;
                rdbChuaXacDinh.Checked = dtTransaction.Rows[0]["Transaction_Unknown"].ToString() == "True" ? true : false;
                rdbKhongCoTiemNang.Checked = dtTransaction.Rows[0]["Transaction_NotPotential"].ToString() == "True" ? true : false;
            }
        }
    }
}